package com.yay.rental.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.yay.rental.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import com.yay.rental.ui.HomeActivity;
import com.yay.rental.ui.RentalApplication;


/**
 * Get Started!
 * @author team@getstarted.com.ua
 */
public class UIUtils {
	private static final String TAG = "UIUtils";
    private static final int BRIGHTNESS_THRESHOLD = 150;
    private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD);
    private static Boolean isOnline;

    public static boolean isOnline(Context context, boolean force) {
		if(isOnline == null || force) {
			try {
				final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
				final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
				if(activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
				    isOnline = true;
				} else {
				    isOnline = false;
				} 
			} catch(Exception e) {
				Log.e(TAG, e.toString());
				isOnline = false;
			}
		}
		return isOnline;
	}
    
    public static Drawable fetchDrawable(String url) {
        if(RentalApplication.getInstance().getDrawableHashMap().containsKey(url)) {
            return RentalApplication.getInstance().getDrawableHashMap().get(url).get();
        }
        InputStream is = null;
        try {
            is = fetch(url);
            Drawable drawable = Drawable.createFromStream(is, "src");
            if(drawable != null) {
            	RentalApplication.getInstance().getDrawableHashMap().put(url, new SoftReference<Drawable>(drawable));
	        }
            return drawable;
        } catch (Exception e) {
            Log.e(TAG, "fetchDrawable failed", e);
            return null;
        } finally {
            if(is != null) {
                try { is.close(); } catch (IOException e) {	}
            }
        }

    }
    
    private static String tjpg = "_t.jpg";
    private static String jpg = ".jpg";
    
    public static void fetchDrawableOnThread(final String url, final View imageView) {
        if(RentalApplication.getInstance().getDrawableHashMap().containsKey(url)) {
            imageView.setBackgroundDrawable(RentalApplication.getInstance().getDrawableHashMap().get(url).get());
        }

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	Drawable drawable = (Drawable) message.obj;
            	if(drawable == null) {
            		if(url.indexOf(tjpg) > 0) { 
            			fetchDrawableOnThread(url.replace(tjpg, jpg), imageView);
            		}
            		imageView.setVisibility(View.GONE);
            	} else {
            		imageView.setBackgroundDrawable(drawable);
            	}
            }
        };

        Thread thread = new Thread() {
            @Override
            public void run() {
                //TODO : set imageView to a "pending" image
            	Drawable drawable = fetchDrawable(url);
                Message message = handler.obtainMessage(1, drawable);
                handler.sendMessage(message);
            }
        };
        thread.start();
    }

    public static InputStream fetch(String url) throws MalformedURLException, IOException {
    	DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);
        return response.getEntity().getContent();
    }

    
    public static void setTitleBarColor(View titleBarView, int color) {
        final ViewGroup titleBar = (ViewGroup) titleBarView;
        titleBar.setBackgroundColor(color);

        /*
         * Calculate the brightness of the titlebar color, based on the commonly known
         * brightness formula:
         *
         * http://en.wikipedia.org/wiki/HSV_color_space%23Lightness
         */
        int brColor = (30 * Color.red(color) +
                       59 * Color.green(color) +
                       11 * Color.blue(color)) / 100;
        if (brColor > BRIGHTNESS_THRESHOLD) {
            ((TextView) titleBar.findViewById(R.id.title_text)).setTextColor(
                    titleBar.getContext().getResources().getColor(R.color.title_text_alt));

            // Iterate through all children of the titlebar and if they're a LevelListDrawable,
            // set their level to 1 (alternate).
            // TODO: find a less hacky way of doing this.
            titleBar.post(new Runnable() {
                public void run() {
                    final int childCount = titleBar.getChildCount();
                    for (int i = 0; i < childCount; i++) {
                        final View child = titleBar.getChildAt(i);
                        if (child instanceof ImageButton) {
                            final ImageButton childButton = (ImageButton) child;
                            if (childButton.getDrawable() != null &&
                                childButton.getDrawable() instanceof LevelListDrawable) {
                                ((LevelListDrawable) childButton.getDrawable()).setLevel(1);
                            }
                        }
                    }
                }
            });
        }
    }

    /**
     * Invoke "home" action, returning to {@link HomeActivity}.
     */
    public static void goHome(Context context) {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    /**
     * Invoke "search" action, triggering a default search.
     */
    public static void goSearch(Activity activity) {
        activity.startSearch(null, false, Bundle.EMPTY, false);
    }

    /**
     * Populate the given {@link TextView} with the requested text, formatting
     * through {@link Html#fromHtml(String)} when applicable. Also sets
     * {@link TextView#setMovementMethod} so inline links are handled.
     */
    public static void setTextMaybeHtml(TextView view, String text) {
        if (text.contains("<") && text.contains(">")) {
            view.setText(Html.fromHtml(text));
            view.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            view.setText(text);
        }
    }

    /**
     * Given a snippet string with matching segments surrounded by curly
     * braces, turn those areas into bold spans, removing the curly braces.
     */
    public static Spannable buildStyledSnippet(String snippet) {
        final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);

        // Walk through string, inserting bold snippet spans
        int startIndex = -1, endIndex = -1, delta = 0;
        while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
            endIndex = snippet.indexOf('}', startIndex);

            // Remove braces from both sides
            builder.delete(startIndex - delta, startIndex - delta + 1);
            builder.delete(endIndex - delta - 1, endIndex - delta);

            // Insert bold style
            builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            delta += 2;
        }

        return builder;
    }
}
